import java.io.IOException;
import java.net.ServerSocket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class SocketExample {

	public static void main(String[] args) throws IOException {
		ServerSocketChannel srvSocketChannel = new ServerSocket(9001)
				.getChannel();
		Selector selector = Selector.open();

		srvSocketChannel.configureBlocking(false);
		srvSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
		ByteBuffer buf = ByteBuffer.allocate(1024);

		while (true) {
			if (selector.select() > 0) {
				final Set<SelectionKey> keys = selector.selectedKeys();
				for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext();) {
					final SelectionKey key = it.next();

					if (key.isAcceptable()) {
						SocketChannel channel = srvSocketChannel.accept();
						channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

					} else if (key.isReadable()) {
						read((SocketChannel)key.channel(), buf);

					} else if (key.isWritable()) {

					}
					it.remove();

				}
			}
		}
	}

	private static void read(SocketChannel channel, ByteBuffer buf)
			throws IOException {
		int bytesRead = channel.read(buf);
		while (bytesRead != -1) {
			buf.flip();
			while (buf.hasRemaining()) {
				System.out.println(buf.get());
			}
			buf.clear();
			bytesRead = channel.read(buf);
		}
	}
	
	
}
